/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.nonmember;

import entity.MemberCustomer;
import entity.Product;
import entity.SaleOrder;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;
import model.ItemCart;
import model.ShoppingCart;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import service.ProductServiceLocal;
import service.SaleOrderDetailServiceLocal;
import service.SaleOrderServiceLocal;

/**
 *
 * @author SONY
 */
public class PaymentStrutsAction extends org.apache.struts.action.Action {
    
    @EJB SaleOrderServiceLocal saleOrderServiceLocal;
    @EJB SaleOrderDetailServiceLocal saleOrderDetailServiceLocal;
    @EJB ProductServiceLocal productServiceLocal;
    
    private UserTransaction ut;

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {        
        try {
            HttpSession session = request.getSession();
            ShoppingCart shopping_cart = (ShoppingCart) session.getAttribute("shopping_cart");
            if(shopping_cart.getQuantityItemCart() > 0) {
                List errorMsgs = new LinkedList();
                String cardnumber = request.getParameter("cardnumber");
                String cardholder = request.getParameter("cardholder");
                String fullname = request.getParameter("fullname");
                String address = request.getParameter("address");
                String phone = request.getParameter("phone");
                double total = Double.parseDouble(request.getParameter("total"));
                if(cardnumber.length() == 0) {
                    errorMsgs.add("Số Thẻ không được bỏ trống.");
                }
                if(cardholder.length() == 0) {
                    errorMsgs.add("Tên Chủ Thẻ không được bỏ trống.");
                }
                request.setAttribute("cardnumber", cardnumber);
                request.setAttribute("cardholder", cardholder);
                request.setAttribute("Name", fullname);
                request.setAttribute("Address", address);
                request.setAttribute("Phone", phone);
                if(errorMsgs.isEmpty()) {
                    ServletContext context = servlet.getServletContext();
                    saleOrderServiceLocal = (SaleOrderServiceLocal) context.getAttribute("saleOrderServiceLocal");
                    List<SaleOrder> lstSaleOrders = saleOrderServiceLocal.getAllSaleOrders();
                    int last_index = lstSaleOrders.size() - 1;
                    SaleOrder last_order = lstSaleOrders.get(last_index);
                    int oid = last_order.getSaleOrderID() + 1;
                    String result = pay(oid, cardnumber, cardholder, total);
                    if(result.equals("Thanh toán thành công.")) {
                        BigDecimal Total = new BigDecimal(total);
                        ArrayList<ItemCart> lstItemCart = shopping_cart.getAllItemCart();
                        Date OrderDate  = new Date();
                        MemberCustomer member = null;
                        if(session.getAttribute("user_member") != null) {
                            member = (MemberCustomer) session.getAttribute("user_member");
                        }
                        try {
                            Context ctx = new InitialContext();
                            ut = (UserTransaction) ctx.lookup("java:comp/UserTransaction");
                            ut.begin(); //start the transactions                        
                            saleOrderDetailServiceLocal = (SaleOrderDetailServiceLocal) context.getAttribute("saleOrderDetailServiceLocal");
                            productServiceLocal = (ProductServiceLocal) context.getAttribute("productServiceLocal");

                            String status = "Mới Đặt";
                            String paymenttype = "Credit Card";
                            SaleOrder saleorder = saleOrderServiceLocal.addSaleOrder(member, fullname, address, phone, OrderDate, status, Total, paymenttype);
                            if(saleorder != null) {
                                for(int i = 0; i < lstItemCart.size(); i++) {
                                    String ProductID = lstItemCart.get(i).getProductID();
                                    int OrderQty = lstItemCart.get(i).getQuantity();
                                    BigDecimal LineTotal = new BigDecimal(lstItemCart.get(i).getTotalLine());
                                    if(saleOrderDetailServiceLocal.addSaleOrderDetail(saleorder, ProductID, OrderQty, LineTotal)) {
                                        //cập nhật lại sl hàng tồn kho khi đặt hàng thành công
                                        Product product = productServiceLocal.getProductDetails_byPID(ProductID);
                                        int QOH = product.getQoh();
                                        int QOH_new = QOH - OrderQty;
                                        if(productServiceLocal.updateQOH_byPID(ProductID, QOH_new)) {
                                            System.out.println("inserted successful!");
                                        }
                                    }
                                }
                            }
                            ut.commit(); //end the transaction
                            shopping_cart.makeEmpty();                        
                            return mapping.findForward(SUCCESS);
                        } catch(Exception e) {
                            System.err.print(e);
                            //xóa dòng vừa thêm vào bảng payment và cập nhật lại số tiền dư cho chủ thẻ
                            if(deletePaymentUpdateBalance(oid, cardnumber, total)) {
                                request.setAttribute("notify", "Thanh Toán Thất Bại.");
                                return mapping.findForward("error");
                            }
                        }
                        request.setAttribute("notify", "Thanh Toán Thất Bại.");
                        return mapping.findForward("error");
                    } else {
                        request.setAttribute("notify", result);
                        return mapping.findForward("error");
                    }
                
                } else {
                    request.setAttribute("errorMsgs", errorMsgs);
                    return mapping.findForward("error");
                }           
            }           
        } catch (Exception e) {
            System.err.println(e);
            //ut.rollback();
            request.setAttribute("notify", "Thanh Toán Thất Bại.");
            return mapping.findForward("error");
        }
        return mapping.findForward("error_cart_empty");
    }

    private static String pay(int arg0, java.lang.String arg1, java.lang.String arg2, double arg3) {
        ws_ref.localhost.PaymentWebServiceService service = new ws_ref.localhost.PaymentWebServiceService();
        ws_ref.localhost.PaymentWebService port = service.getPaymentWebServicePort();
        return port.pay(arg0, arg1, arg2, arg3);
    }

    private static boolean deletePaymentUpdateBalance(int arg0, java.lang.String arg1, double arg2) {
        ws_ref.localhost.PaymentWebServiceService service = new ws_ref.localhost.PaymentWebServiceService();
        ws_ref.localhost.PaymentWebService port = service.getPaymentWebServicePort();
        return port.deletePaymentUpdateBalance(arg0, arg1, arg2);
    }
}
